<?php
namespace App\Models;

use Illuminate\Support\Facades\DB;

class Worktime extends BaseModel
{
    protected $table = "work_time";


    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        return $this->multiSelect($fields)->multiWhere($where)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }

    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getGroupList(array $where = [], $fields = '*', $order = '', $group = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->multiGroup($group)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->multiGroup($group)->get();
        }

    }

    /**
     * 根据条件删除数据
     */
    public function del(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
//        dd($data);
        return $this->insertGetId($data);
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        return $this->multiWhere($where)->update($data);
    }

    /**
     * 获取和
     */
    public function getSum($where, $field)
    {
        return $this->multiWhere($where)->sum($field);
    }

    /**
     * 字段递加
     */
    public function inc($where, $field, $n)
    {
        return $this->multiWhere($where)->increment($field, $n);
    }

    public function doctor()
    {
        return $this->belongsTo('App\Models\Doctor', 'doctor_id', 'id');
    }


    public function getWorkTime($request){
         $where['id'] = $request['id'];
         $data = $this->getOne($where);
         $doctor = new Doctor();
         $d_where['id'] = $data['doctor_id'];
         $d_info = $doctor->getOne($d_where);
         $data['time_area'] = json_decode($data['time_area']);
         $data['doc_name'] = $d_info['name'];
         if($data){
             $data = $data->toArray();
         }
         return $data;
    }

    public function changeWorkSate($request){
         $where['id'] = $request['id'];
         $updata['status'] = $request['status'];
         $res = $this->up($where,$updata);
         if(!$res){
             return ['state'=>0,'msg'=>'修改失败'];
         }
         return ['state'=>1,'msg'=>'修改成功'];
    }

    /**
     * 删除坐诊计划
     * @param $request
     * @return mixed
     */
    public function getDelWorkTime($request){
        $res = $this->del(['id'=>$request['id']]);
        $data['status'] = $res ? 1 : 0;
        $data['msg'] = '删除失败';
        if ($res) {
            $data['msg'] = '删除成功';
        }
        return $data;
    }

    public function getWorkTimeIndex()
    {
        $where = [];
        $order['id'] = "desc";
        $pageLine = 10;
        if(isset($_GET['page'])){
              $startLimet = ($_GET['page']-1)*$pageLine;
        }else{
              $startLimet = 0;
        }
        $count = DB::table('work_time')->count();
        $data = DB::table('work_time')->groupBy('doctor_id')->skip($startLimet)->take($pageLine)->get();
        $rowId = array('');
        $row = [];
        $key = 0;
        $doctor = new Doctor();
        foreach ($data as $k => $v) {
            $where['doctor_id'] = $v->doctor_id;
            $order['add_time'] = "desc";
            $res = $this->getList($where, "*", $order);
            if (!in_array($v->doctor_id, $rowId)) {
                $rowId[] = $v->doctor_id;
                $d_where['d_id'] = $v->id;
                $d_info = $doctor->getDoctorById($d_where);
                $row[$k]['id'] = $v->id;
                $row[$k]['apointment_type'] = $v->apointment_type;
                $row[$k]['work_type'] = $v->work_type;
                $row[$k]['id'] = $v->id;
                $row[$k]['id'] = $v->id;
//             $data[$k]['time_area'] = json_decode($v['time_area']);
                $row[$k]['d_status'] = $d_info['data']['status'];
                $row[$k]['doc_name'] = $d_info['data']['name'];
                $row[$k]['last_time'] = $res[count($res)-1]['add_time'];
                $key++;
            }
        }
        if ($data) {
            $page = ceil($count/$pageLine);
            $pageNoList = [];
            for($i=1;$i<$page;$i++){
                $pageNoList[] = $i;
            }
            $data['current_page'] = isset($_GET['page'])?$_GET['page']:1;
            $data['pageNoList'] = $pageNoList;
        }
        $data['data']= $row;
        return $data;
    }

    public function getWorkTimeList(){
        $where = [];
        $order['id'] = "desc";
        $data = $this->getList($where,'*',$order,10);
        if($data){
            $data = $data->toArray();
            $data['pageNoList'] = getPageNoList($data['last_page'], request('page', 1), 10);
        }
        $rowId = array('');
        $row = [];
        $key = 0;
        $doctor = new Doctor();
        foreach($data['data'] as $k => $v){
             $where['doctor_id'] = $v['doctor_id'];
             $order['add_time'] = "desc";
             $res = $this->getList($where,"*",$order);
             if(!in_array($v['doctor_id'],$rowId)){
                   $row[$key] = $v;
                   $rowId[] = $v['doctor_id'];
                   $d_where['id'] = $v['id'];
                   $d_info = $doctor->getOne($d_where);
//             $data[$k]['time_area'] = json_decode($v['time_area']);
                   $row[$key]['doc_name'] = $d_info['name'];
                   $row[$key]['last_time'] = $res['0']['add_time'];
                   $key++;
             }

        }
        return $row;
    }

    /**
     * 返回某条医师的工作排班
     */
    public function getWorkTimeListById($request){
        $where['doctor_id'] = $request['id'];
        $order['add_time'] = 'asc';
        $data = $this->getList($where,'*',$order,10);
        if(!$data){
            return ['state'=>0,'msg'=>"预约信息错误"];
        }
        $data = $data->toArray();
        $data['pageNoList'] = getPageNoList($data['last_page'], request('page', 1), 10);
        $doctor = new Doctor();
        $d_where['id'] = $where['doctor_id'];
        $d_info = $doctor->getOne($d_where);
        foreach($data['data'] as $key => $v){
               $data['data'][$key]['doc_name'] = $d_info['name'];
               $data['data'][$key]['time_arr'] = json_decode($v['time_area']);
        }
        return $data;
    }

    /**
     *  获取一条排班数据
     */
    public function getWorkTimeByIdOne($request){
        $where['id'] = $request['id'];
        $order['add_time'] = 'asc';
        $data = $this->getOne($where,'*',$order,10);
        if(!$data){
            return ['state'=>0,'msg'=>"预约信息错误"];
        }
        $data = $data->toArray();
        $data['time_arr'] = explode(',',$data['time_area']);
        return $data;
    }

    /**
     * 返回某条医师的工作排班
     */
    public function getWorkTimeById($request){
           $where['doctor_id'] = $request['id'];
           if($request['key']) {
               $where['add_time'] = date('Y-m-d',strtotime("+".$request['key']." day"));
           }else{
               $where['add_time'] = date('Y-m-d',strtotime("+1". "day"));
           }
           $order['add_time'] = 'asc';
           $data = $this->getOne($where,'*',$order,10);
           if(!$data){
                 return ['state'=>0,'msg'=>"预约信息错误"];
           }
           $data = $data->toArray();
           $doctor = new Doctor();
           $appoint = new Appointment();
           $d_where['id'] = $data['doctor_id'];
           $d_info = $doctor->getOne($d_where);
           $timeArrea = json_decode($data['time_area']);
           $data['d_name'] = $d_info['name'];
           $time_area = [];
           foreach($timeArrea as $key => $value) {
                    $date = $where['add_time'].' '.$value;
                     // 判断本人是否预约
                     $appointwhere['user_id'] = $request['mid'];
                     $appointwhere['doctor_id'] = $where['doctor_id'];
                     $appointwhere['mark_time'] = strtotime($date);
                     $appointwhere['status'] = 1;
                     $app_res = $appoint->getOne($appointwhere);
                     $is_app = 0;
                     if($app_res){
                          $is_app = 1;
                     }
                     if(isset($today)){
                       $time_area[$key]['today'] = 1;
                     }
                     $time_area[$key]['time'] = $value;
                     $time_area[$key]['is_app'] = $is_app;

                     // 判断该时段是否有人预约
                     $a_where['doctor_id'] = $where['doctor_id'];
                     $a_where['mark_time'] = strtotime($date);
                     $a_where['status'] = 1;
                     $has_app = $appoint->getOne($a_where);
                     $av_app = 1;
                     if($has_app){
                         $av_app = 0;
                     }
                     $time_area[$key]['av_app'] = $av_app;
           }

           $data['time_area1'] = $time_area;
           return $data;
    }

    /**
     * @param 编辑医师排班日期
     * @return
     */
    public function editDcotorWorkTime($request){
        $d_id = $request['d_id'];
        if(empty($d_id)){
            return  "医师id为空";
        }
        $appiont_type = intval($request['appiont_type']);
        $work_type = intval($request['work_type']);
        if(empty($appiont_type)||empty($work_type)){
            return  "预约类型不能为空或工作时间不能为空";
        }
        $time_area = $request['time_area'];
        $data['doctor_id'] = $d_id;
        $data['apointment_type'] = $appiont_type;
        $data['work_type'] = $work_type;
        $data['time_area'] = json_encode($time_area);
        $data['add_time'] = $request['time'];
        $data['status'] = 1;
        $data['updated_at'] = date("Y-m-d",time());
        $where['id'] = $request['id'];
        $res = $this->up($where,$data);
        if(!$res){
            return  "编辑医师工作时间失败";
        }
        return  "编辑医师工作时间成功";
    }

    public function getTest(){
        for($i=0;$i<40;$i++) {
            $time_area = array('9:00','9:30');
            $data['doctor_id'] = 7+$i;
            $data['apointment_type'] = 1;
            $data['work_type'] = 1;
            $data['time_area'] = json_encode($time_area) ;
            $data['add_time'] = date('Y-m-d');
            $data['status'] = 1;
            $data['created_at'] = date("Y-m-d", time());
            $data['updated_at'] = date("Y-m-d", time());
            $did = $this->add($data);
            $res = ['state' => 1, 'msg' => "医师编辑成功"];
        }
    }

    /**
     * @param 添加医师排班日期
     * @return
     */
    public function addDcotorWorkTime($request){
        $day = $request['daylist'];
        $d_id = $request['d_id'];
        if(empty($d_id)){
              return ['state'=>1,'msg'=>'医师id错误'];
        }
        $appiont_type = intval($request['appiont_type']);
        $work_type = intval($request['work_type']);
        if (empty($appiont_type) || empty($work_type)) {
            return "预约类型不能为空或工作时间不能为空";
        }
        $count = 1;
        $insertResulte = []; // 保存结果数据
        foreach($day as $k => $v){
            $where['add_time'] = $v;
            $where['doctor_id'] = $d_id;
            $res = $this->getOne($where);
            if ($res) {
                $insertResulte['resulte'] = 'false';
                $insertResulte['log'] = "该日期已列入计划";
                $insertResulte['data'] = $v;
                continue;
            }
            $time_area = $request['time_area'];
            $data['doctor_id'] = $d_id;
            $data['apointment_type'] = $appiont_type;
            $data['work_type'] = $work_type;
            $data['time_area'] = json_encode($time_area);
            $data['add_time'] = $v;
            $data['status'] = 1;
            $data['created_at'] = date("Y-m-d", time());
            $res = $this->add($data);
            if(!$res){
                $insertResulte['resulte'] = 'false';
                $insertResulte['log'] = "该日期插入失败";
                $insertResulte['data'] = $v;
                continue;
            }
            $insertResulte['resulte'] = true;
            $insertResulte['log'] = "该日期插入成功";
            $insertResulte['data'] = $v;
            $count++;
        }
        if(count($day)==$count){
                 return "数据全部插入成功";
//               return ['state'=>1,'msg'=>"数据全部插入成功",'data'=>$insertResulte];
        }
        return "数据部分插入成功";
//        return ['state'=>0,'msg'=>"部分插入成功",'data'=>$insertResulte];
    }
}